package net.mihome.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.R;
import net.mihome.app.bean.FriendList;
import net.mihome.app.bean.MyInformation;
import net.mihome.app.bean.Result;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 用户资料
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class UserInfo extends BaseActivity {

	private View back;
	private ImageView refresh;
	private ImageView face;
	private ImageView gender;
	private Button editer;
	
	private TextView name;
	private TextView jointime;
	private TextView moTextView;
	private TextView emTextView;
	private TextView realNameTextView;
	
	private TextView from;
	private TextView devplatform;
	private TextView expertise;
	private TextView followers;
	private TextView emailTextView;
	private TextView favorites;
	private TextView communityTextView;
	private TextView companyTextView;
	private TextView addressTextView;
	private LinearLayout updateRealNameLinearLayout;
	private LinearLayout updateEmailLinearLayout;
	private LinearLayout updateAddressLinearLayout;
	private LinearLayout followers_ll;
	private LinearLayout fans_ll;
	private LoadingDialog loading;
	private MyInformation user;
//	private Handler mHandler;
    public final static int TO_FRESH_USER_INFO=200;
	private final static int CROP = 200;
	private final static String FILE_SAVEPATH = Environment
			.getExternalStorageDirectory().getAbsolutePath()
			+ "/OSChina/Portrait/";
	private Uri origUri;
	private Uri cropUri;
	private File protraitFile;
	private Bitmap protraitBitmap;
	private String protraitPath;
    private Button myBigpaperBtn;

    private Integer uid;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_info);

		// 初始化视图控件
		this.initView();
		// 初始化视图数据
//		this.initData();
	}

	private void initView() {
        myBigpaperBtn= (Button) findViewById(R.id.user_info_my_bigpaper);
		back = (View) findViewById(R.id.user_info_back);
		refresh = (ImageView) findViewById(R.id.user_info_refresh);
		editer = (Button) findViewById(R.id.user_info_editer);
		back.setOnClickListener(UIHelper.finish(this));
		refresh.setOnClickListener(refreshClickListener);
		editer.setOnClickListener(editerClickListener);
		communityTextView=(TextView) findViewById(R.id.user_info_community_name);
		face = (ImageView) findViewById(R.id.shop_info_userface);
		gender = (ImageView) findViewById(R.id.user_info_gender);
		name = (TextView) findViewById(R.id.user_info_username);
		realNameTextView=(TextView) findViewById(R.id.user_info_realname);
        addressTextView= (TextView) findViewById(R.id.user_info_address);
		emailTextView=(TextView) findViewById(R.id.user_info_email);
		moTextView=(TextView) findViewById(R.id.user_info_mobile);
		companyTextView=(TextView) findViewById(R.id.user_info_company_name);
		jointime = (TextView) findViewById(R.id.user_info_jointime);
        updateRealNameLinearLayout = (LinearLayout) findViewById(R.id.user_info_favorites_ll);
        updateEmailLinearLayout = (LinearLayout) findViewById(R.id.user_info_fans_ll);
        updateAddressLinearLayout = (LinearLayout) findViewById(R.id.user_info_address_layout);
        updateRealNameLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(UserInfo.this,UpdateUserActivity.class);
                intent.putExtra("title","修改真实姓名");
                intent.putExtra("item_name","realname");
                intent.putExtra("show_name","姓名:");
                startActivityForResult(intent, TO_FRESH_USER_INFO);
            }
        });
        updateEmailLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(UserInfo.this,UpdateUserActivity.class);
                intent.putExtra("title","修改邮箱");
                intent.putExtra("item_name","email");
                intent.putExtra("show_name","邮箱:");
                startActivityForResult(intent, TO_FRESH_USER_INFO);
            }
        });
        updateAddressLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(UserInfo.this,UpdateUserActivity.class);
                intent.putExtra("title","修改住址");
                intent.putExtra("item_name","address");
                intent.putExtra("show_name","住址:");
                startActivityForResult(intent, TO_FRESH_USER_INFO);
            }
        });
        myBigpaperBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(uid!=null&&uid>0){
                    Intent intent=new Intent(UserInfo.this,DazibaoActivity.class);
                    intent.putExtra("id",uid);
                    startActivity(intent);
                }else{
                    UIHelper.showAlertDialog(UserInfo.this,"提示","用户信息无效");
                }
            }
        });
	}

	private void initData() {
		this.loadUserInfoThread(false);
	}

	private void loadUserInfoThread(final boolean isRefresh) {
		loading = new LoadingDialog(this);
		loading.show();
		final Message msg = new Message();
		 ((AppContext) getApplication()).getMyInformation(isRefresh,new MiAsyncHttpResponseHandler<Map>() {
			@Override
			public void onSuccess(int arg0, Header[] arg1,ResponsePojo<Map> responsePojo) {
				MyInformation user=MyInformation.parse(responsePojo.getData());
                uid=user.getId();
				// 加载用户头像
				UIHelper.showUserFace(face, user.getAvatar());
				// 用户性别
				if (user.getSex() == 0)
					gender.setImageResource(R.drawable.widget_gender_man);
				else
					gender.setImageResource(R.drawable.widget_gender_woman);
				// 其他资料
				name.setText(user.getUsername());
				jointime.setText(StringUtils.friendly_time(user
						.getJointime()));
				emailTextView.setText(user.getEmail());
				moTextView.setText(user.getMobile());
				realNameTextView.setText(user.getRealname());
				if(user.getCommunity()!=null){
					communityTextView.setText(user.getCommunity().getName());
				}
				if(user.getCompany()!=null){
					companyTextView.setText(user.getCompany().getFullName());
				}
                addressTextView.setText(user.getAddress());
				loading.dismiss();
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
				Toast.makeText(UserInfo.this,arg3.getMessage(),Toast.LENGTH_SHORT).show();
				loading.dismiss();
			}
		});
	}

	private View.OnClickListener editerClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			CharSequence[] items = { getString(R.string.img_from_album),
					getString(R.string.img_from_camera) };
			imageChooseItem(items);
		}
	};

	private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			loadUserInfoThread(true);
		}
	};

	private View.OnClickListener favoritesClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.showUserFavorite(v.getContext());
		}
	};

	private View.OnClickListener fansClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			int followers = user != null ? user.getFollowerscount() : 0;
			int fans = user != null ? user.getFanscount() : 0;
			UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FANS,
					followers, fans);
		}
	};

	private View.OnClickListener followersClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			int followers = user != null ? user.getFollowerscount() : 0;
			int fans = user != null ? user.getFanscount() : 0;
			UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FOLLOWER,
					followers, fans);
		}
	};

	// 裁剪头像的绝对路径
	private Uri getUploadTempFile(Uri uri) {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

		// 如果是标准Uri
		if (StringUtils.isEmpty(thePath)) {
			thePath = ImageUtils.getAbsoluteImagePath(UserInfo.this, uri);
		}
		String ext = FileUtils.getFileFormat(thePath);
		ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
		// 照片命名
		String cropFileName = "osc_crop_" + timeStamp + "." + ext;
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);

		cropUri = Uri.fromFile(protraitFile);
		return this.cropUri;
	}

	// 拍照保存的绝对路径
	private Uri getCameraTempFile() {
		String storageState = Environment.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			File savedir = new File(FILE_SAVEPATH);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		} else {
			UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像，请检查SD卡是否挂载");
			return null;
		}
		String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date());
		// 照片命名
		String cropFileName = "osc_camera_" + timeStamp + ".jpg";
		// 裁剪头像的绝对路径
		protraitPath = FILE_SAVEPATH + cropFileName;
		protraitFile = new File(protraitPath);
		cropUri = Uri.fromFile(protraitFile);
		this.origUri = this.cropUri;
		return this.cropUri;
	}

	/**
	 * 操作选择
	 * 
	 * @param items
	 */
	public void imageChooseItem(CharSequence[] items) {
		AlertDialog imageDialog = new AlertDialog.Builder(this)
				.setTitle("上传头像").setIcon(android.R.drawable.btn_star)
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						// 相册选图
						if (item == 0) {
							startImagePick();
						}
						// 手机拍照
						else if (item == 1) {
							startActionCamera();
						}
					}
				}).create();

		imageDialog.show();
	}

	/**
	 * 选择图片裁剪
	 * 
	 */
	private void startImagePick() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		startActivityForResult(Intent.createChooser(intent, "选择图片"),
				ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
	}

	/**
	 * 相机拍照
	 * 
	 */
	private void startActionCamera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
		startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
	}

	/**
	 * 拍照后裁剪
	 * 
	 * @param data
	 *            原始图片
	 *            裁剪后图片
	 */
	private void startActionCrop(Uri data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(data, "image/*");
		intent.putExtra("output", this.getUploadTempFile(data));
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", CROP);// 输出图片大小
		intent.putExtra("outputY", CROP);
		intent.putExtra("scale", true);// 去黑边
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边
		startActivityForResult(intent,
				ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
	}

	/**
	 * 上传新照片
	 */
	private void uploadNewPhoto() {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
                    loading.hide();
					loading.dismiss();
				if (msg.what == 1 && msg.obj != null) {
					Result res = (Result) msg.obj;
						// 显示新头像
					face.setImageBitmap(protraitBitmap);
				} else if (msg.what == -1 && msg.obj != null) {
					loading.setLoadText("上传出错·");
					loading.hide();
					((AppException) msg.obj).makeToast(UserInfo.this);
				}else if(msg.what == -2){
					loading.setLoadText("图像不存在，上传失败·");
					loading.hide();
				}
			}
		};

		if (loading != null) {
			loading.setLoadText("正在上传头像···");
			loading.show();
		}

		new Thread() {
			public void run() {
				// 获取头像缩略图
				if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
					protraitBitmap = ImageUtils.loadImgThumbnail(protraitPath,
							200, 200);
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							loading.setLoadText("图像不存在，上传失败·");
							loading.hide();
						}
					});
				}

				if (protraitBitmap != null) {
					Message msg = new Message();
					try {
						Result res = ((AppContext) getApplication())
								.updatePortrait(protraitFile);
						if (res != null && res.OK()) {
							// 保存新头像到缓存
							String filename = FileUtils.getFileName(user
									.getFace());
							ImageUtils.saveImage(UserInfo.this, filename,
									protraitBitmap);
						}
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						msg.what = -1;
						msg.obj = e;
					} catch (IOException e) {
						e.printStackTrace();
					}
					handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = -2;
                    handler.sendMessage(msg);
				}
			};
		}.start();
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		if (resultCode != RESULT_OK)
			return;

		switch (requestCode) {
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
			startActionCrop(origUri);// 拍照后裁剪
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
			startActionCrop(data.getData());// 选图后裁剪
			break;
		case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD: {
            uploadNewPhoto();// 上传新照片
            break;
        }
        case TO_FRESH_USER_INFO:{
            loadUserInfoThread(true);
            break;
        }
        default:{
            loadUserInfoThread(true);
        }
		}
	}

    @Override
    protected void onResume() {
        loadUserInfoThread(true);
        super.onResume();
    }
}
